package com.ke.searchhouse.security;

import com.ke.searchhouse.base.LoginUserUtil;
import com.ke.searchhouse.entity.User;
import com.ke.searchhouse.service.ISmsService;
import com.ke.searchhouse.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
@Slf4j
public class AuthFilter extends UsernamePasswordAuthenticationFilter{
    @Autowired
    private ISmsService smsService;
    @Autowired
    private IUserService userService;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {

       String username = obtainUsername(request);
       if (StringUtils.isNotBlank(username)) {
           request.setAttribute("username", username);
           return super.attemptAuthentication(request, response);
       }

       String telephone = request.getParameter("telephone");
       if (StringUtils.isBlank(telephone) || !LoginUserUtil.checkTelephone(telephone)) {
           throw new BadCredentialsException("Wrong telephone number");
       }

        User user = userService.findUserByTelephone(telephone);
        String inputCode = request.getParameter("smsCode");
        String sessionCode = smsService.getSmsCode(telephone);

        log.info("inputCode:{}, sessionCode:{}", inputCode, sessionCode);

        if (Objects.equals(inputCode, sessionCode)) {
            smsService.remove(telephone);

             // 第一次登陆，创建用户
            if (user == null) {
                user = userService.addUserByPhone(telephone);
            }
            return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        } else {
            throw new BadCredentialsException("smsCode error");
        }

    }
}
